//
//  EmoticonPackage.swift
//  表情键盘
//
//  Created by Jacky Sun on 16/5/25.
//  Copyright © 2016年 syf. All rights reserved.


import UIKit
import Foundation
/*
 结构:
 1. 加载emoticons.plist拿到每组表情的路径
 
 emoticons.plist(字典)  存储了所有组表情的数据
 |----packages(字典数组)
 |-------id(存储了对应组表情对应的文件夹)
 
 2. 根据拿到的路径加载对应组表情的info.plist
 info.plist(字典)
 |----id(当前组表情文件夹的名称)
 |----group_name_cn(组的名称)
 |----emoticons(字典数组, 里面存储了所有表情)
 |----chs(表情对应的文字)
 |----png(表情对应的图片)
 |----code(emoji表情对应的十六进制字符串)
 */

class EmoticonPackage: NSObject {

    /// 当前组表情文件s?的名称
    var id: String?
    /// 组的名称
    var group_name_cn : String?
    /// 当前组所有的表情对象
    var emoticons: [Emotion]?
    
    // 标记最近组里添加了几个表情
    var times: Int = 0
    
    /// 写一个单例， 依次加载所有表情
    static let packageList: [EmoticonPackage] = EmoticonPackage.loadPackages()
    
    /**
     获取所有组的表情数组
    */
   private  class func loadPackages() ->[EmoticonPackage] {
        // 创建模型数组
        var packages = [EmoticonPackage]()
        
        let package = EmoticonPackage(id: "")
        package.group_name_cn = "最近"
        package.emoticons = [Emotion]()
        package.appendLastPageEmotions()
        packages.append(package)
        
        // 1、 写出字符串路径
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        let dict = NSDictionary(contentsOfFile: path)
        let dictArr = dict!["packages"] as! [[String: AnyObject]]
        
        for dict in dictArr{
            let package = EmoticonPackage(id: dict["id"] as! String)
            // 设置对象的emotion和 group 属性
             package.loadEveryEmotion()
             package.appendLastPageEmotions()
             packages.append(package)
          }
          return packages
    }
    
    init(id: String) {
        super.init()
        self.id = id
    }
    
    
    //MARK: - 获取每一组的所有表情
    func loadEveryEmotion(){
    let path  =  (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle") as NSString
    let path_2 = (path.stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent("info.plist")
        
        // 字典
        let dict =  NSDictionary(contentsOfFile: path_2)
        
        let dictArr = dict!["emoticons"] as! [[String: AnyObject]]
         group_name_cn = dict!["group_name_cn"] as? String

            emoticons =  [Emotion]()
        
        //  因为每一组的每一页都要添加一个删除按钮
        // 保证没20个表情后插入一个删除按钮
           var index = 0
            for emo in dictArr
            {
                // 确保插入的加好按钮后面有表情
              if index == 20{
                    emoticons?.append( Emotion(ISDeleteBtn: true))
                    index = 0
                }
                emoticons?.append(Emotion(dict: emo, id: id!))
                index += 1
            }
    }
    
    //MARK: - 为了不让两组表情有在同一页的情况， 补齐前面一组最优一页不足21的表情说量
    func appendLastPageEmotions(){
        let count = emoticons!.count % 21
       // print("total = \(emoticons?.count)   count= \(count)")

        for _ in count..<20{
            emoticons?.append(Emotion(ISDeleteBtn: false))
            }
        emoticons?.append(Emotion(ISDeleteBtn: true))
    }
    
    
    //MARK: -m 添加最近的使用的表情
    func addRecentEmotion(emotion: Emotion){
        times += 1
        emotion.times = times
        
       // print("times = \(emotion.times)")
        if  emotion.ISDeleteBtn == true{
            return
        }

        // 移除最后面的删除按钮
        emoticons!.removeLast()
        
       let ISAddedLast = emoticons!.contains(emotion)
        // 如果没有添加，则添加到表情
        if !ISAddedLast{
            // 没添加一个新的元素， 就要删除一个旧的元素
            emoticons!.removeLast()
            emoticons!.append(emotion)
        }
        else
        {// 如有已经有一个
            
            for (index, dict) in emoticons!.enumerate()// 产生元组
            {
                
                if dict == emotion
                {
                    emoticons!.removeAtIndex(index)
                }
            }
            emoticons!.append(emotion)
        }
        
       var result = emoticons?.sort({ (e1, e2) -> Bool in
            return e1.times > e2.times
        })
        // 添加最后面的删除的按钮
        result?.append(Emotion(ISDeleteBtn: true))
     
      emoticons = result
    }
    
    
  
    //MARK: - 根据表情文字返回表情所对应的模型
   class func returnEmotionMOodelByEmotionText(emotionStr: String) ->Emotion{
        
        var emotion: Emotion?
        for  package in EmoticonPackage.packageList{
            emotion =  package.emoticons?.filter({ (e) -> Bool in
                return e.chs ==  emotionStr
            }).last
            
            if emotion != nil{
                break
            }
        }
        return emotion!
    }
    
    
    //MARK: -m  返回label需要额attribute
    class func returnAttritbute(statusText: String, font: UIFont) ->NSAttributedString?{
        let newAttrubuteStr: NSMutableAttributedString = NSMutableAttributedString(string: statusText)
        newAttrubuteStr.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, statusText.characters.count))
        let paragraphStyle: NSMutableParagraphStyle  = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 3
        
        newAttrubuteStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range:  NSMakeRange(0, statusText.characters.count))
        do{
            let pattern = "\\[.*?\\]"
            let regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
            let checkingResults =  regex.matchesInString(statusText, options: .ReportProgress, range: NSMakeRange(0, statusText.characters.count))
            
            // checkingResults.reverse()
            // 倒叙便利数组
            for checking in checkingResults.reverse()
            {
                let emotionStr =  (statusText as NSString).substringWithRange(checking.range)
                print(emotionStr)
                let emotion =  returnEmotionMOodelByEmotionText(emotionStr)
                let attrbuteStr = EmojiAttachment.imageText(emotion, font: font)
                
                //替换字符属性
                newAttrubuteStr.replaceCharactersInRange(checking.range, withAttributedString: attrbuteStr)
            }
            
             return newAttrubuteStr
        }
        catch{
            print(error)
            return nil
        }
    }
    
}


class Emotion: NSObject {
    /// 表情对应的文字
    var chs: String?
    
    /// 表情对应的图片
    var png: String?{
        didSet{
            let path = (((NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle") as NSString).stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!)
            imgPath = path
        }
    }
    
    /// emoji表情对应的十六进制字符串
    var code: String?{
        didSet{
            //1、从字符串中取出十六进制数
            // 创建一个扫描器， 从扫描器中读取扫描到的数据
             let scanner = NSScanner(string: code!)
            
            //2. 将十六进制转换为字符串
            var result: UInt32 = 0
            scanner.scanHexInt(&result)
                        
            //将十六进制装换为 emoji字符串
            emojiStr = "\(Character(UnicodeScalar(result)))"
            
        }
    }
    
     /// emoji表情真正的字符串
    var emojiStr: String?
    
    /// 当前表情对应的文件夹
    var id: String?
    
    // 图片的真实路径
    var imgPath: String?
    
    /// 是不是删除按钮的标示
    var ISDeleteBtn: Bool = false
    
    // 标记当前表情被使用的次数
    var times: Int = 0
    
    // 创建一个新的构造方法
    init(dict: [String: AnyObject], id: String){
        super.init()
        self.id = id
       setValuesForKeysWithDictionary(dict)
    }
    
    init(ISDeleteBtn: Bool) {
        super.init()
        self.ISDeleteBtn = ISDeleteBtn
    }
    
    // 重写此方法是防止 KVC 转 中 出现的问题
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
}
